<?php
class Breg {
/**
* Callbacks for functions defined in the regex
*/
public $handlers = [];
/**
* @param $function_name the name of the reg function to handle
* @param $callable a callable that returns a string replacement
*/
public function handle(string $function_name, callable $callable){
$this->handlers[$function_name] = $callable;
}
/**
* Match 'better' regex against a string
* @param $regex to parse & `preg_match` with
* @param $string to search within
* @return matches from `preg_match_all(..., PREG_SET_ORDER)` after parsing
*/
public function match($regex, $string){
$reg = $this->parse($regex);
$didMatch = preg_match_all($regex, $string, $matches, PREG_SET_ORDER);
return $matches;
}
/**
* Parse the regex, then call all `::functions()` & fill in the regex with their results
* @param $regex;
*/
public function parse($regex){
$parser = new \Breg\Parser();
$parsed = $parser->parse($regex);
$clean = $parsed['clean_reg'];
foreach ($parsed['functions'] as $f){
$handler = $this->handlers[$f['name']];
$replacement = $handler(...$f['args']);
$clean = str_replace($f['definition'], $replacement, $clean);
}
return $clean;
}
}